﻿using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Threading;
using Codeflows;
using Codeflows.Recovery;
using CodeflowsHost.Configuration;

namespace CodeflowsHost
{
    class CodeflowsRecoveryService : CustomServiceBase
    {
        Timer _timer;
        TimeSpan _interval;

        public CodeflowsRecoveryService()
        {
            LoadConfiguration();
        }

        void LoadConfiguration()
        {
            var configuration = CodeflowHostConfigurationSection.GetConfiguration();
            _interval = TimeSpan.FromMinutes(configuration.Interval);
        }

        public override void Start()
        {            
            _timer = new Timer(OnInterrupt, null, Timeout.Infinite, Timeout.Infinite);
            _timer.Change(0, Timeout.Infinite);
        }

        public override void Stop()
        {            
        }

        protected override string GetServiceName()
        {
            return "Codeflows Recovery Service";
        }

        void OnInterrupt(object state)
        {
            DiagnosticsUtility.Verbose("Sending retry command {0}.", DateTime.Now);

            using (var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Codeflows"].ConnectionString))
            {
                ControlMessageSender.SendRretry(sqlConnection);
            }

            _timer.Change(_interval, TimeSpan.FromMilliseconds(-1));
        }
    }
}